﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FirstFloor.ModernUI.Windows.Controls;
using Lephone.Data;

namespace SimlvClient.Pages
{
    /// <summary>
    /// PageCatch.xaml 的交互逻辑
    /// </summary>
    public partial class PageCatch : System.Windows.Controls.UserControl
    {
        public PageCatch()
        {
            InitializeComponent();
        }

        private void BtnAll_Click_1(object sender, RoutedEventArgs e)
        {

            CreatPage Page = new CreatPage();
            Page.UpdatePage();
            //AllAoShuPage();
        }

        private void AllEngLish()
        {
 
        }

        /// <summary>
        /// 奥数 6年级 5年级 4年级部分
        /// </summary>
        private void AllAoShuPage()
        {
            var AoShuCategoryLists = DbEntry.From<SimlvClient.Model.StuAoCategory>().Where(Lephone.Data.Condition.Empty).OrderByDescending(o => o.Id).Select().ToList();
            foreach (var CateModel in AoShuCategoryLists)
            {
                System.Windows.Forms.WebBrowser webb;
                HtmlDocument htmldoc;
                CreatDoc(out webb, out htmldoc);

                string strWebContent = GetWebContent(CateModel.Url.ToString());
                htmldoc.Write(strWebContent);



                HtmlElementCollection htmlOption = htmldoc.GetElementsByTagName("option");

                foreach (HtmlElement Option in htmlOption)
                {
                    HtmlElementCollection htmlul;
                    System.Windows.Forms.WebBrowser webb0;
                    HtmlDocument htmldoc0;
                    CreatDoc(out webb0, out htmldoc0);
                    string href = Option.GetAttribute("value");
                    if (href != CateModel.Url.ToString())
                    {


                        string strWebContent0 = GetWebContent(href);
                        htmldoc0.Write(strWebContent0);

                        htmlul = htmldoc0.GetElementsByTagName("ul");
                    }
                    else
                    {
                        htmlul = htmldoc.GetElementsByTagName("ul");
                    }
                    #region
                    foreach (HtmlElement ul in htmlul)
                    {
                        string Htmlclass = ul.GetAttribute("className");
                        if (Htmlclass == "listing1")
                        {
                            HtmlElementCollection htmlaList = ul.GetElementsByTagName("a");
                            foreach (HtmlElement AModel in htmlaList)
                            {
                                System.Windows.Forms.WebBrowser webb1;
                                HtmlDocument htmldoc1;
                                CreatDoc(out webb1, out htmldoc1);
                                string Url = AModel.GetAttribute("href").Replace("about:", "");
                                string strWebContent1 = GetWebContent(Url);
                                htmldoc1.Write(strWebContent1);
                                HtmlElementCollection htmlh1List = htmldoc1.GetElementsByTagName("h1");
                                string AoShuTitle = string.Empty;
                                string AoshuContent = string.Empty;
                                string Answer = string.Empty;
                                foreach (HtmlElement h1Model in htmlh1List)
                                {
                                    string Htmlh1Class = h1Model.GetAttribute("className");
                                    if (Htmlh1Class == "title")
                                    {
                                        AoShuTitle = h1Model.InnerText;
                                    }
                                }
                                HtmlElementCollection htmlContentDiv = htmldoc1.GetElementsByTagName("div");
                                foreach (HtmlElement ContentModel in htmlContentDiv)
                                {
                                    string HtmlContentDivClass = ContentModel.GetAttribute("className");
                                    if (HtmlContentDivClass == "mainContent")
                                    {
                                        HtmlElementCollection htmlContentP = ContentModel.GetElementsByTagName("p");
                                        foreach (HtmlElement ContentModelP in htmlContentP)
                                        {
                                            HtmlElementCollection htmlContentImg = ContentModelP.GetElementsByTagName("img");
                                            foreach (HtmlElement ImgModel in htmlContentImg)
                                            {
                                                string ImgName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                                                string ImgSrc = ImgModel.GetAttribute("src").Replace("about:", "");
                                                SavePhotoFromUrl("AoshuImg/" + ImgName + ".jpg", ImgSrc);
                                                AoshuContent = AoshuContent + "\r\n" + "{$Img:" + ImgName + "}";
                                            }
                                            AoshuContent = AoshuContent + "\r\n" + ContentModelP.InnerText;
                                        }
                                    }
                                }
                                webb1.Dispose();
                                System.Windows.Forms.WebBrowser webb2;
                                HtmlDocument htmldoc2;
                                CreatDoc(out webb2, out htmldoc2);

                                string strWebContent2 = GetWebContent(Url.Replace(".html", "_2.html"));
                                htmldoc2.Write(strWebContent2);
                                HtmlElementCollection htmlContentDiv2 = htmldoc2.GetElementsByTagName("div");
                                foreach (HtmlElement ContentModel2 in htmlContentDiv2)
                                {
                                    string HtmlContentDivClass2 = ContentModel2.GetAttribute("className");
                                    if (HtmlContentDivClass2 == "mainContent")
                                    {
                                        HtmlElementCollection htmlContentP = ContentModel2.GetElementsByTagName("p");
                                        foreach (HtmlElement ContentModelP in htmlContentP)
                                        {
                                            HtmlElementCollection htmlContentImg = ContentModelP.GetElementsByTagName("img");
                                            foreach (HtmlElement ImgModel in htmlContentImg)
                                            {
                                                string ImgName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                                                string ImgSrc = ImgModel.GetAttribute("src").Replace("about:", "");
                                                SavePhotoFromUrl("AoshuImg/" + ImgName + ".jpg", ImgSrc);
                                                Answer = Answer + "\r\n" + "{$Img:" + ImgName + "}";
                                            }
                                            Answer = Answer + "\r\n" + ContentModelP.InnerText;
                                        }
                                    }
                                }
                                Model.StuAoShu AoShuModel = new Model.StuAoShu();
                                AoShuModel.Answer = Answer;
                                AoShuModel.Cid = CateModel.Id;
                                AoShuModel.Question = AoshuContent.Replace("点击下一页查看答案>>>", "");
                                AoShuModel.Title = AoShuTitle;
                                AoShuModel.Save();
                                webb2.Dispose();
                            }
                        }
                    }
                    #endregion
                    webb0.Dispose();
                }

                webb.Dispose();
            }
        }


        /// <summary>
        /// 成语关联
        /// </summary>
        private void AllIdiomRelation()
        {
            var IdiomLists = DbEntry.From<SimlvClient.Model.StuBook>().Where(Lephone.Data.Condition.Empty).OrderByDescending(o => o.Id).Select().ToList();
            var IdiomList = DbEntry.From<SimlvClient.Model.StuIdiom>().Where(Lephone.Data.Condition.Empty).OrderByDescending(o => o.Id).Select().ToList();
            foreach (var Model in IdiomList)
            {
                System.Windows.Forms.WebBrowser webb;
                HtmlDocument htmldoc;
                CreatDoc(out webb, out htmldoc);

                string strWebContent = GetWebContent("http://shici.chazidian.com" + Model.Url.ToString());
                htmldoc.Write(strWebContent);
                HtmlElementCollection htmlDiv = htmldoc.GetElementsByTagName("div");
                foreach (HtmlElement div in htmlDiv)
                {
                    string Htmlclass = div.GetAttribute("className");
                    if (Htmlclass == "list150")
                    {
                        HtmlElementCollection aList = div.GetElementsByTagName("a");
                        foreach (HtmlElement TagA in aList)
                        {
                            string IdiomName = TagA.GetAttribute("title");
                            var ParentId = IdiomList.Where(o => o.Idiom == IdiomName).SingleOrDefault().Id;
                            SimlvClient.Model.StuIdiomRelation StuIdiomModel = new SimlvClient.Model.StuIdiomRelation();
                            StuIdiomModel.Idiom = Model.Id;//Id
                            StuIdiomModel.ParentId = ParentId;
                            StuIdiomModel.Save();
                        }
                    }
                }
                webb.Dispose();
            }

        }

        /// <summary>
        /// 成语故事
        /// </summary>
        private void AllIdiomPage()
        {

            for (int j = 1; j < 5; j++)
            {
                System.Windows.Forms.WebBrowser webb;
                HtmlDocument htmldoc;
                CreatDoc(out webb, out htmldoc);

                string strWebContent = GetWebContent("http://shici.chazidian.com/chengyugushi/?page=" + j.ToString());
                htmldoc.Write(strWebContent);
                HtmlElementCollection htmlDiv = htmldoc.GetElementsByTagName("div");
                foreach (HtmlElement div in htmlDiv)
                {
                    string Htmlclass = div.GetAttribute("className");
                    if (Htmlclass == "list150")
                    {
                        HtmlElementCollection aList = div.GetElementsByTagName("a");
                        foreach (HtmlElement TagA in aList)
                        {
                            string IdiomName = TagA.GetAttribute("title");
                            string Url = TagA.GetAttribute("href").Replace("about:", "");
                            System.Windows.Forms.WebBrowser webb1;
                            HtmlDocument Subhtmldoc;
                            CreatDoc(out webb1, out Subhtmldoc);

                            string SubContent = GetWebContent("http://shici.chazidian.com" + Url);
                            Subhtmldoc.Write(SubContent);
                            HtmlElementCollection SubDivs = Subhtmldoc.GetElementsByTagName("div");
                            string AllContent = string.Empty;

                            foreach (HtmlElement subd in SubDivs)
                            {
                                if (subd.GetAttribute("className") == "discription")
                                {
                                    AllContent = subd.InnerText;
                                    break;
                                }
                            }
                            char expectNChar = '\n';
                            char expectRChar = '\r';
                            var ContentList = AllContent.Split(expectNChar);
                            string NewContent = string.Empty;
                            bool IsStart = false;
                            for (int i = 0; i < ContentList.Length; i++)
                            {
                                if (ContentList[i].Contains("访问："))
                                {
                                    IsStart = true;
                                    continue;
                                }
                                else if (ContentList[i].Contains("标签："))
                                {
                                    IsStart = false;
                                    continue;
                                }
                                if (IsStart)
                                {
                                    NewContent = NewContent + ContentList[i];
                                }
                            }
                            string Ne = NewContent.Trim(expectRChar);
                            Model.StuIdiom StuIdiomModel = new Model.StuIdiom();
                            StuIdiomModel.Idiom = IdiomName;
                            StuIdiomModel.IContent = Ne;
                            StuIdiomModel.Url = Url;
                            StuIdiomModel.Save();
                        }
                    }
                    else if (Htmlclass != "")
                    {

                    }
                }
            }
        }

        /// <summary>
        /// 诗词 小学类
        /// </summary>
        private void AllPoetryOtherPage()
        {
            System.Windows.Forms.WebBrowser webb;
            HtmlDocument htmldoc;
            CreatDoc(out webb, out htmldoc);

            string strWebContent = GetWebContent("http://shici.chazidian.com/gushidaquan/xiaoxue/");
            htmldoc.Write(strWebContent);
            HtmlElementCollection htmlDiv = htmldoc.GetElementsByTagName("div");
            foreach (HtmlElement div in htmlDiv)
            {
                string Htmlclass = div.GetAttribute("className");
                if (Htmlclass == "box")
                {
                    HtmlElementCollection divList = div.GetElementsByTagName("div");
                    long HeaderId = 0;
                    foreach (HtmlElement DivElement in divList)
                    {
                        if (DivElement.GetAttribute("className") == "menu_title")
                        {
                            string CategoryName = DivElement.InnerText;
                            HeaderId = DbEntry.From<SimlvClient.Model.StuPoetryCategory>().Where(o => o.CategoryName == CategoryName).Select().SingleOrDefault().Id;
                        }
                        if (DivElement.GetAttribute("className") == "list100")
                        {
                            HtmlElementCollection aElementList = DivElement.GetElementsByTagName("a");
                            foreach (HtmlElement aElement in aElementList)
                            {
                                string Url = aElement.GetAttribute("href").Replace("about:", "");
                                string PoetryName = aElement.GetAttribute("title");
                                var PoetryModel = DbEntry.From<SimlvClient.Model.StuPoetry>().Where(o => o.PoetryName == PoetryName).Select().SingleOrDefault();
                                if (PoetryModel != null)
                                {
                                    if (!string.IsNullOrEmpty(PoetryModel.CateId))
                                    {
                                        PoetryModel.CateId = PoetryModel.CateId + "," + HeaderId.ToString();
                                    }
                                    else
                                    {
                                        PoetryModel.CateId = HeaderId.ToString();
                                    }
                                    PoetryModel.Save();
                                }
                                else
                                {
                                    System.Windows.Forms.WebBrowser webb1;
                                    HtmlDocument Subhtmldoc;
                                    CreatDoc(out webb1, out Subhtmldoc);

                                    string SubContent = GetWebContent("http://shici.chazidian.com" + Url);
                                    Subhtmldoc.Write(SubContent);
                                    HtmlElementCollection SubDivs = Subhtmldoc.GetElementsByTagName("div");
                                    string AutherName = string.Empty;
                                    string AllContent = string.Empty;
                                    string Note = string.Empty;
                                    string Translation = string.Empty;
                                    string Analyze = string.Empty;
                                    char expectNChar = '\n';
                                    char expectRChar = '\r';
                                    foreach (HtmlElement subd in SubDivs)
                                    {
                                        if (subd.GetAttribute("className") == "discription")
                                        {
                                            AllContent = subd.InnerText;

                                        }
                                        else if (subd.GetAttribute("className") == "info")
                                        {
                                            if (subd.InnerText != null && subd.InnerText != "")
                                            {
                                                AutherName = subd.InnerText.Replace("作者：", "");
                                            }
                                        }
                                    }

                                    var ContentList = AllContent.Split(expectNChar);
                                    string NewContent = string.Empty;
                                    bool IsStart = false;
                                    bool IsNote = false;
                                    bool IsTranslation = false;
                                    bool IsAnalyze = false;
                                    for (int i = 0; i < ContentList.Length; i++)
                                    {
                                        if (ContentList[i].Contains("作者："))
                                        {
                                            IsStart = true;
                                            continue;
                                        }
                                        else if (ContentList[i].Contains("标签："))
                                        {
                                            IsAnalyze = false;
                                            IsTranslation = false;
                                            IsNote = false;
                                            IsStart = false;
                                            continue;
                                        }
                                        else if (ContentList[i].Contains("注解") || ContentList[i].Contains("注释"))
                                        {
                                            IsNote = true;
                                            IsStart = false;
                                            continue;
                                        }
                                        else if (ContentList[i].Contains("译文"))
                                        {
                                            IsTranslation = true;
                                            IsNote = false;
                                            IsStart = false;
                                            continue;
                                        }
                                        else if (ContentList[i].Contains("赏析"))
                                        {
                                            IsAnalyze = true;
                                            IsTranslation = false;
                                            IsNote = false;
                                            IsStart = false;
                                            continue;
                                        }
                                        if (IsStart)
                                        {
                                            NewContent = NewContent + ContentList[i];
                                        }
                                        if (IsNote)
                                        {
                                            Note = Note + ContentList[i];
                                        }
                                        if (IsTranslation)
                                        {
                                            Translation = Translation + ContentList[i];
                                        }
                                        if (IsAnalyze)
                                        {
                                            Analyze = Analyze + ContentList[i];
                                        }
                                    }
                                    string Ne = NewContent.Trim(expectRChar);
                                    Model.StuPoetry StuPoetryModel = new Model.StuPoetry();
                                    StuPoetryModel.Author = AutherName;
                                    StuPoetryModel.PoetryName = PoetryName;
                                    StuPoetryModel.Note = Note;
                                    StuPoetryModel.Translation = Translation;
                                    StuPoetryModel.Analyze = Analyze;
                                    StuPoetryModel.CateId = HeaderId.ToString();
                                    StuPoetryModel.PContent = Ne;
                                    StuPoetryModel.Save();
                                    webb1.Dispose();
                                }
                            }
                        }

                    }
                }
                else if (Htmlclass != "")
                {

                }
            }
            webb.Dispose();
        }

        /// <summary>
        /// 诗词 唐诗
        /// </summary>
        private void AllPoetryPage()
        {
            System.Windows.Forms.WebBrowser webb;
            HtmlDocument htmldoc;
            CreatDoc(out webb, out htmldoc);

            string strWebContent = GetWebContent("http://shici.chazidian.com/gushidaquan/tangshi/");
            htmldoc.Write(strWebContent);
            HtmlElementCollection htmlDiv = htmldoc.GetElementsByTagName("div");
            foreach (HtmlElement div in htmlDiv)
            {
                string Htmlclass = div.GetAttribute("className");
                if (Htmlclass == "box")
                {
                    HtmlElementCollection divList = div.GetElementsByTagName("div");
                    long HeaderId = 0;
                    foreach (HtmlElement DivElement in divList)
                    {
                        if (DivElement.GetAttribute("className") == "menu_title")
                        {
                            string CategoryName = DivElement.InnerText;
                            HeaderId = DbEntry.From<SimlvClient.Model.StuPoetryCategory>().Where(o => o.CategoryName == CategoryName).Select().SingleOrDefault().Id;
                        }
                        if (DivElement.GetAttribute("className") == "list100")
                        {
                            HtmlElementCollection aElementList = DivElement.GetElementsByTagName("a");
                            foreach (HtmlElement aElement in aElementList)
                            {
                                string Url = aElement.GetAttribute("href").Replace("about:", "");
                                string PoetryName = aElement.GetAttribute("title");
                                System.Windows.Forms.WebBrowser webb1;
                                HtmlDocument Subhtmldoc;
                                CreatDoc(out webb1, out Subhtmldoc);

                                string SubContent = GetWebContent("http://shici.chazidian.com" + Url);
                                Subhtmldoc.Write(SubContent);
                                HtmlElementCollection SubDivs = Subhtmldoc.GetElementsByTagName("div");
                                string AutherName = string.Empty;
                                string AllContent = string.Empty;
                                string Note = string.Empty;
                                string Translation = string.Empty;
                                string Analyze = string.Empty;
                                char expectNChar = '\n';
                                char expectRChar = '\r';
                                foreach (HtmlElement subd in SubDivs)
                                {
                                    if (subd.GetAttribute("className") == "discription")
                                    {
                                        AllContent = subd.InnerText;
                                        #region
                                        //HtmlElementCollection SubPs=  subd.GetElementsByTagName("p");
                                        //foreach (HtmlElement Subp in SubPs)
                                        //{
                                        //    if (Subp.GetAttribute("align") == "center")
                                        //    {
                                        //        AllContent = Subp.InnerText;
                                        //    }
                                        //    else if (Subp.Children[0].InnerText == "注解")
                                        //    {
                                        //        Note = Subp.InnerText.Replace("注解", "").Trim(expectRChar);
                                        //    }
                                        //    else if (Subp.Children[0].InnerText == "译文")
                                        //    {
                                        //        Translation = Subp.InnerText.Replace("译文", "").Trim(expectRChar);
                                        //    }
                                        //    else if (Subp.Children[0].InnerText == "赏析")
                                        //    {
                                        //        Analyze = Subp.InnerText.Replace("赏析", "").Trim(expectRChar);
                                        //    }
                                        //}
                                        #endregion
                                    }
                                    else if (subd.GetAttribute("className") == "info")
                                    {
                                        if (subd.InnerText != null && subd.InnerText != "")
                                        {
                                            AutherName = subd.InnerText.Replace("作者：", "");
                                        }
                                    }
                                }

                                var ContentList = AllContent.Split(expectNChar);
                                string NewContent = string.Empty;
                                bool IsStart = false;
                                bool IsNote = false;
                                bool IsTranslation = false;
                                bool IsAnalyze = false;
                                for (int i = 0; i < ContentList.Length; i++)
                                {
                                    if (ContentList[i].Contains("作者："))
                                    {
                                        IsStart = true;
                                        continue;
                                    }
                                    else if (ContentList[i].Contains("标签："))
                                    {
                                        IsAnalyze = false;
                                        IsTranslation = false;
                                        IsNote = false;
                                        IsStart = false;
                                        continue;
                                    }
                                    else if (ContentList[i].Contains("注解") || ContentList[i].Contains("注释"))
                                    {
                                        IsNote = true;
                                        IsStart = false;
                                        continue;
                                    }
                                    else if (ContentList[i].Contains("译文"))
                                    {
                                        IsTranslation = true;
                                        IsNote = false;
                                        IsStart = false;
                                        continue;
                                    }
                                    else if (ContentList[i].Contains("赏析"))
                                    {
                                        IsAnalyze = true;
                                        IsTranslation = false;
                                        IsNote = false;
                                        IsStart = false;
                                        continue;
                                    }
                                    if (IsStart)
                                    {
                                        NewContent = NewContent + ContentList[i];
                                    }
                                    if (IsNote)
                                    {
                                        Note = Note + ContentList[i];
                                    }
                                    if (IsTranslation)
                                    {
                                        Translation = Translation + ContentList[i];
                                    }
                                    if (IsAnalyze)
                                    {
                                        Analyze = Analyze + ContentList[i];
                                    }
                                }
                                string Ne = NewContent.Trim(expectRChar);
                                Model.StuPoetry StuPoetryModel = new Model.StuPoetry();
                                StuPoetryModel.Author = AutherName;
                                StuPoetryModel.PoetryName = PoetryName;
                                StuPoetryModel.Note = Note;
                                StuPoetryModel.Translation = Translation;
                                StuPoetryModel.Analyze = Analyze;
                                StuPoetryModel.CateId = HeaderId.ToString();
                                StuPoetryModel.PContent = Ne;
                                StuPoetryModel.Save();
                                webb1.Dispose();
                            }
                        }

                    }
                }
                else if (Htmlclass != "")
                {

                }
            }
            webb.Dispose();
        }


        private void SubPage()
        {
            //var CategoryList = DbEntry.From<SimlvClient.Model.StuCategory>().Where(Lephone.Data.Condition.Empty).OrderByDescending(o => o.Id).Select().ToList();
            System.Windows.Forms.WebBrowser webb;
            HtmlDocument htmldoc;
            CreatDoc(out webb, out htmldoc);
            string strWebContent = GetWebContent("http://www.xiexingcun.com/ertong/lizhiwei04.htm");
            htmldoc.Write(strWebContent);
            string ChapterName = "abcd";
            string ChapterContent = string.Empty;
            ChapterContent = (((mshtml.HTMLDocumentClass)(htmldoc.DomDocument)).documentElement).innerText;
            HtmlElementCollection TagList = htmldoc.GetElementsByTagName("table");
            ChapterContent = TagList[1].InnerText;
            Model.StuBookChapter SubChapter = new Model.StuBookChapter();
            SubChapter.BookId = 9999;
            SubChapter.ChapterContent = ChapterContent.Trim('|');
            SubChapter.ChapterName = ChapterName;
            SubChapter.Save();
            webb.Dispose();
        }

        /// <summary>
        /// 世界名著
        /// </summary>
        private void AllWorldPage()
        {
            var CategoryList = DbEntry.From<SimlvClient.Model.StuCategory>().Where(Lephone.Data.Condition.Empty).OrderByDescending(o => o.Id).Select().ToList();

            System.Windows.Forms.WebBrowser webb;
            HtmlDocument htmldoc;
            CreatDoc(out webb, out htmldoc);
            string strWebContent = GetWebContent("http://www.xiexingcun.com/World/index.htm");
            htmldoc.Write(strWebContent);
            HtmlElementCollection htmlinput = htmldoc.GetElementsByTagName("A");
            foreach (HtmlElement TagA in htmlinput)
            {
                string href = TagA.GetAttribute("href").Replace("about:", "");
                if (href.Contains("index.htm"))
                {
                    string Id = href.Replace("/index.htm", "");

                    //string Src = TagA.Children[0].GetAttribute("src").Replace("about:", "");
                    //string BookName = Src.Replace("图片/", "").Replace(".jpg", "").Replace("about:", "");
                    string BookName = TagA.InnerText;
                    long CateId = 0;
                    var CateModel = CategoryList.Where(o => o.SourceId.Split(',').Any(j => j == Id)).FirstOrDefault();
                    if (CateModel != null)
                    {
                        CateId = CateModel.Id;
                    }
                    Model.StuBook bookModel = new Model.StuBook();
                    bookModel.Cid = CateId;
                    bookModel.BookName = BookName;
                    bookModel.SourceAddress = href;
                    bookModel.Save();
                    System.Windows.Forms.WebBrowser webb1;
                    HtmlDocument Subhtmldoc;
                    CreatDoc(out webb1, out Subhtmldoc);

                    string SubCategoryContent = GetWebContent("http://www.xiexingcun.com/World/" + href);
                    Subhtmldoc.Write(SubCategoryContent);

                    HtmlElementCollection htmlTable = Subhtmldoc.GetElementsByTagName("A");
                    foreach (HtmlElement htmla in htmlTable)
                    {
                        if (htmla.GetAttribute("HREF").Contains(".htm"))
                        {
                            string ChapterName = htmla.InnerText;
                            string ContentSrc = htmla.GetAttribute("HREF").Replace("about:", "");
                            string SubHTMLContent = GetWebContent("http://www.xiexingcun.com/World/" + Id + "/" + ContentSrc);
                            System.Windows.Forms.WebBrowser webb2;
                            HtmlDocument Subhtmlcontent;
                            CreatDoc(out webb2, out Subhtmlcontent);
                            Subhtmlcontent.Write(SubHTMLContent);
                            var ContentHtml = Subhtmlcontent.GetElementsByTagName("p");
                            string ChapterContent = string.Empty;
                            // ChapterContent = (((mshtml.HTMLDocumentClass)(Subhtmlcontent.DomDocument)).documentElement).innerText;
                            HtmlElementCollection TagList = Subhtmlcontent.GetElementsByTagName("table");
                            ChapterContent = TagList[1].InnerText;
                            Model.StuBookChapter SubChapter = new Model.StuBookChapter();
                            SubChapter.BookId = bookModel.Id;
                            SubChapter.ChapterContent = ChapterContent.Trim('|');
                            SubChapter.ChapterName = ChapterName;
                            SubChapter.Save();
                            webb2.Dispose();
                        }
                    }

                }
            }
        }
        /// <summary>
        /// 童话
        /// </summary>
        private void AllPage()
        {
            var CategoryList = DbEntry.From<SimlvClient.Model.StuCategory>().Where(Lephone.Data.Condition.Empty).OrderByDescending(o => o.Id).Select().ToList();

            System.Windows.Forms.WebBrowser webb;
            HtmlDocument htmldoc;
            CreatDoc(out webb, out htmldoc);
            string strWebContent = GetWebContent("http://www.xiexingcun.com/ertong/index.htm");
            htmldoc.Write(strWebContent);
            HtmlElementCollection htmlinput = htmldoc.GetElementsByTagName("A");
            foreach (HtmlElement TagA in htmlinput)
            {
                string href = TagA.GetAttribute("href").Replace("about:", "");
                if (href.Contains("index") && href.Contains(".htm"))
                {
                    string Id = href.Replace("index", "").Replace(".htm", "");

                    string Src = TagA.Children[0].GetAttribute("src").Replace("about:", "");
                    string BookName = Src.Replace("图片/", "").Replace(".jpg", "").Replace("about:", "");
                    long CateId = 0;
                    var CateModel = CategoryList.Where(o => o.SourceId.Split(',').Any(j => j == Id)).FirstOrDefault();
                    if (CateModel != null)
                    {
                        CateId = CateModel.Id;
                    }
                    Model.StuBook bookModel = new Model.StuBook();
                    bookModel.Cid = CateId;
                    bookModel.BookName = BookName;
                    bookModel.SourceAddress = href;
                    SavePhotoFromUrl("bookImg/" + BookName + ".jpg", "http://www.xiexingcun.com/ertong/" + Src);
                    bookModel.BookPic = "bookImg/" + BookName + ".jpg";
                    bookModel.Save();
                    System.Windows.Forms.WebBrowser webb1;
                    HtmlDocument Subhtmldoc;
                    CreatDoc(out webb1, out Subhtmldoc);

                    string SubCategoryContent = GetWebContent("http://www.xiexingcun.com/ertong/" + href);
                    Subhtmldoc.Write(SubCategoryContent);

                    HtmlElement htmlTable = Subhtmldoc.GetElementById("table4");
                    foreach (HtmlElement tbbody in htmlTable.Children)
                    {
                        var Alist = tbbody.GetElementsByTagName("a");

                        foreach (HtmlElement Aelement in Alist)
                        {
                            string ChapterName = Aelement.InnerText;
                            string ContentSrc = Aelement.GetAttribute("href").Replace("about:", "");
                            string SubHTMLContent = GetWebContent("http://www.xiexingcun.com/ertong/" + ContentSrc);
                            System.Windows.Forms.WebBrowser webb2;
                            HtmlDocument Subhtmlcontent;
                            CreatDoc(out webb2, out Subhtmlcontent);
                            Subhtmlcontent.Write(SubHTMLContent);
                            var ContentHtml = Subhtmlcontent.GetElementsByTagName("p");
                            string ChapterContent = string.Empty;
                            // ChapterContent = (((mshtml.HTMLDocumentClass)(Subhtmlcontent.DomDocument)).documentElement).innerText;
                            HtmlElementCollection TagList = Subhtmlcontent.GetElementsByTagName("table");
                            ChapterContent = TagList[1].InnerText;
                            Model.StuBookChapter SubChapter = new Model.StuBookChapter();
                            SubChapter.BookId = bookModel.Id;
                            SubChapter.ChapterContent = ChapterContent.Trim('|');
                            SubChapter.ChapterName = ChapterName;
                            SubChapter.Save();
                            webb2.Dispose();
                        }
                    }

                }
            }
        }

        private static void CreatDoc(out System.Windows.Forms.WebBrowser webb, out HtmlDocument htmldoc)
        {
            webb = new System.Windows.Forms.WebBrowser();
            webb.ScriptErrorsSuppressed = true;
            webb.Navigate("about:blank");
            htmldoc = webb.Document.OpenNew(true);
        }


        private string GetWebContent(string Url)
        {
            string strResult = "";
            try
            {
            s:
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                //声明一个HttpWebRequest请求 
                request.Timeout = 30000;
                //设置连接超时时间 
                //request.Headers.Set("Pragma", "no-cache");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream streamReceive = response.GetResponseStream();
                Encoding encoding = Encoding.GetEncoding("utf-8");
                StreamReader streamReader = new StreamReader(streamReceive, encoding);
                strResult = streamReader.ReadToEnd();


            }
            catch
            {
                // MessageBox.Show("出错");
            }
            return strResult;
        }

        public static bool SavePhotoFromUrl(string FileName, string Url)
        {
            bool Value = false;
            WebResponse response = null;
            Stream stream = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

                response = request.GetResponse();
                stream = response.GetResponseStream();

                if (!response.ContentType.ToLower().StartsWith("text/"))
                {
                    Value = SaveBinaryFile(response, FileName);

                }

            }
            catch (Exception err)
            {
                string aa = err.ToString();
            }
            return Value;
        }
        /// <summary>
        /// Save a binary file to disk.
        /// </summary>
        /// <param name="response">The response used to save the file</param>
        // 将二进制文件保存到磁盘
        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            bool Value = true;
            byte[] buffer = new byte[1024];

            try
            {
                if (File.Exists(FileName))
                    File.Delete(FileName);
                Stream outStream = System.IO.File.Create(FileName);
                Stream inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);

                outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }
    }
}
